<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>代码雨</title>
		<style>
			* {
				margin: 0;
				padding: 0	;
			}
			body {
				overflow: hidden;
			}
			canvas {
				background-color: #000;
				width: 100vw;
				height: 100vh;
			}
		</style>
	</head>
	<body>
		<canvas id="codeBox"></canvas>
		<script>
			const codeBox = document.querySelector("#codeBox");
			const ctx = codeBox.getContext("2d");
			console.log(devicePixelRatio * window.innerWidth);
			function init() {
				codeBox.width  = window.innerWidth * devicePixelRatio;
				codeBox.height = window.innerHeight * devicePixelRatio;
			}
			init();
			// devicePixelRatio设备像素比，根据这个计算字体大小
			const fontSize = 20 * devicePixelRatio;
			// 设置字体和大小
			ctx.font = `${fontSize}px "Consolas"`;
			// 计算列数
			const columnCount = Math.floor(codeBox.width / fontSize); 
			const charIndex = new Array(columnCount).fill(0);
			// 绘制函数
			function draw() {
				// 设置渐隐的效果，通过绘制覆盖的先后顺序形成渐变的效果，
				ctx.fillStyle = "rgba(0, 0, 0, 0.1)";
				ctx.fillRect(0, 0, codeBox.width, codeBox.height);
				ctx.fillStyle = "#6de445";
				// 设置文本基线为顶部
				ctx.textBaseline = "top";
				for (var i = 0; i < columnCount; i++) {
					const text = getRandomChar();
					const x = i * fontSize;
					const y = charIndex[i] * fontSize;
					ctx.fillText(text, x, y);
					// 这个时间点开始随机错开
					if (y > codeBox.height && Math.random() > 0.99) {
						charIndex[i] = 0;
					} else {
						charIndex[i]++;
					}
				}
			}
			setInterval(draw, 50);
			// 获取随机字符
			function getRandomChar() {
				const str = "qwertyuiopasdfghjklzcxvbnm1234567980";
				return str[Math.floor(Math.random() * str.length)];
			}
		</script>
	</body>
</html>